//**************************************************************
//		PrefPaneController.m
//			AppHider
//
//	Copyright (c) 2008 Metta Media
//
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//**************************************************************
#import "PrefPaneController.h"

@implementation PrefPaneController
- (id) init
{
	self = [super init];
	if (self != nil) {
		credits = [[NSAttributedString alloc] initWithRTF:[NSData dataWithContentsOfFile:[[[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHider"] resourcePath] stringByAppendingPathComponent:@"Credits.rtf"]] documentAttributes:NULL];
		NSString * shortVersion = [[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHider"] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
		NSString * longVersion = [[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHider"] objectForInfoDictionaryKey:@"CFBundleVersion"];
		version = [NSString stringWithFormat:@"version %@/%@", shortVersion, longVersion];
		//[SUUpdater updaterForBundle:[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHiderDaemon"]];// setFeedURL:[NSURL URLWithString:@"http://foolsworkshop.com/downloads/sparklesample.xml"]];
		//[updater setDelegate:self];
		[daemonSlider setState:[self isDaemonRunning]];
		/* if(AXAPIEnabled())
			{
				[guiScriptingState setStringValue:@"GUI Scripting Enabled"];
				[guiScriptingStateIcon setImage:[[NSImage alloc] initWithContentsOfFile:[[[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHider"] resourcePath] stringByAppendingPathComponent:@"GreenDot.png"]]];
				[guiScriptingButton setTitle:@"Disable"];
			} */
		//Add Daemon to login items
		MMLoginItems * loginItems = [[MMLoginItems alloc] init];
		NSString *pathToDaemon = [[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHiderDaemon"] bundlePath];
		if ([[NSNumber numberWithInt:[startUpCheck state]] boolValue]) {
			if (![loginItems isLoginItem:pathToDaemon]) {
				[loginItems addLoginItem:pathToDaemon hidden:NO];
			}
		}
		[loginItems release];
	}
	return self;
}

-(void)awakeFromNib
{
	[daemonSlider setState:[self isDaemonRunning]];
	/* if(AXAPIEnabled())
		{
			[guiScriptingState setStringValue:@"GUI Scripting Enabled"];
			[guiScriptingStateIcon setImage:[[NSImage alloc] initWithContentsOfFile:[[[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHider"] resourcePath] stringByAppendingPathComponent:@"GreenDot.png"]]];
			[guiScriptingButton setTitle:@"Disable"];
		}
		else
		{
			[guiScriptingState setStringValue:@"GUI Scripting Disabled"];
			[guiScriptingStateIcon setImage:[[NSImage alloc] initWithContentsOfFile:[[[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHider"] resourcePath] stringByAppendingPathComponent:@"RedDot.png"]]];
			[guiScriptingButton setTitle:@"Enable"];
		} */
	
}

-(IBAction)showAboutPrefs:(id)sender
{
	[appTable deselectRow:[appTable selectedRow]];
	[mainView selectTabViewItemWithIdentifier:@"aboutTab"];
}

-(IBAction)export:(id)sender
{
	if([appTable selectedRow] > -1)
	{
		NSSavePanel * savePanel = [[NSSavePanel savePanel] retain];
		id delegate = [appTable delegate];
		NSString * app = [delegate performSelector:@selector(nameOfSelectedApplication)];
		NSArray * name = [app componentsSeparatedByString:@"."];
		NSString * file = [name objectAtIndex:0];
		[savePanel setDirectory:[@"~/Desktop/" stringByExpandingTildeInPath]];
		[savePanel setExtensionHidden:YES];
		[savePanel setAccessoryView:exporterContentView];
		NSLog(@"Whack 1");
		[savePanel beginSheetForDirectory:[@"~/Desktop/" stringByExpandingTildeInPath] 
									 file:file 
						   modalForWindow:[NSApp mainWindow] 
							modalDelegate:self 
						   didEndSelector:@selector(didEndSaveSheet:returnCode:conextInfo:)
							  contextInfo:nil];
		NSLog(@"Whack 2");
	}
	else{
		NSBeep();
	}
}

-(IBAction)import:(id)sender
{
	NSOpenPanel *import = [NSOpenPanel openPanel];
	[import setCanChooseFiles:YES];
	[import setCanChooseDirectories:NO];
	[import setAllowsMultipleSelection:NO];
	//[import setAccessoryView:addAppExtraView];
	[import beginSheetForDirectory:@"/Applications/"
									   file:nil
									  types:[NSArray arrayWithObjects:@"app",@"plist",nil]
							 modalForWindow:[NSApp mainWindow]
							  modalDelegate:self
							 didEndSelector:@selector(openPanelDidEnd:
													  returnCode:
													  contextInfo:)
							    contextInfo:nil];
}
-(void)openPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
	if(returnCode == NSOKButton)
	{
		NSString * appPath = [[panel filename] stringByExpandingTildeInPath];
		[panel orderOut:nil];
		[NSApp endSheet:panel];
		if([[appPath pathExtension] isEqualTo:@"app"])
		{
			BOOL isDirectory;
			NSFileManager * fm = [NSFileManager defaultManager];
			if([fm fileExistsAtPath:[appPath stringByAppendingString:@"/Applications/"] isDirectory:&isDirectory] && isDirectory)
			{
				NSArray * files = [fm directoryContentsAtPath:[appPath stringByAppendingString:@"/Applications/"]];
				NSEnumerator * fileEnumerator = [files objectEnumerator];
				id app;
				while(app = [fileEnumerator nextObject])
				{
					[[appTable delegate] performSelector:@selector(importAppFromPath:) withObject:app];
				}
			}
		}
		else
		{
			[[appTable delegate] performSelector:@selector(importAppFromPath:) withObject:appPath];
		}
	}
}


-(void)didEndSaveSheet:(NSSavePanel *)panel returnCode:(int)returnCode conextInfo:(void *)contextInfo
{
	if (returnCode = NSFileHandlingPanelOKButton) {
		NSLog(@"filename: %@", [panel filename]);
		[[appTable delegate] performSelector:@selector(saveAppTo:extension:) withObject:[[panel filename] stringByAppendingString:([[exporterType titleOfSelectedItem] isEqualToString:@"AppHider File"]?@".plist":@".app")] withObject:([[exporterType titleOfSelectedItem] isEqualToString:@"AppHider File"]?@"plist":@"app")];
	}
}

-(BOOL)isDaemonRunning
{
	return ([AGProcess processForCommand:@"AppHider Daemon"] != nil);
}

/* -(IBAction)toggleDaemon:(id)sender
{
	if([self isDaemonRunning])
	{
		[self terminateDaemon];
		[daemonSlider setState:NO];
	}
	else
	{
		[self launchDaemon];
		[daemonSlider setState:NO];
	}
} */

-(void)launchDaemon
{
	//NSLog(@"path is %@",[[[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHider"] bundlePath] stringByAppendingString:@"Contents/MacOS/AppHider Daemon.app"]);
	[[NSWorkspace sharedWorkspace] launchApplication:[[[NSBundle bundleWithIdentifier:@"com.mettamedia.AppHider"] bundlePath] stringByAppendingString:@"/Contents/MacOS/AppHider Daemon.app"]];//AppWithBundleIdentifier:@"com.mettamedia.AppHiderDaemon" options:NSWorkspaceLaunchAsync additionalEventParamDescriptor:nil launchIdentifier:nil];
}
	 
-(void)terminateDaemon
{
	 OSStatus err;
	 AppleEvent event, reply;
	 
	 const char *bundleIDString = [@"com.mettamedia.AppHiderDaemon" UTF8String];
	 
	 err = AEBuildAppleEvent(kCoreEventClass, kAEQuitApplication,
							 typeApplicationBundleID, 
							 bundleIDString, strlen(bundleIDString),
							 kAutoGenerateReturnID, kAnyTransactionID,
							 &event, NULL, "");
	 
	 if (err == noErr) {
		err = AESendMessage(&event, &reply, kAENoReply, kAEDefaultTimeout);
		(void)AEDisposeDesc(&event);
	 }
	 else
	 {
		NSException* myException = [NSException
								 exceptionWithName:@"DaemonCouldNotQuit"
								 reason:@"Daemon was unable to quit using apple events"
								 userInfo:nil];
		@throw myException;
	 }
}

-(IBAction)togggleGuiScripting:(id)sender
{
	//see if it's on maybe with PFAssstive or AXElement
}

- (IBAction) openURL:(id) sender {
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.mettamedia.com"]];
}

/*- (BOOL)updater:(SUUpdater *)updater shouldPostponeRelaunchForUpdate:(SUAppcastItem *)update untilInvoking:(NSInvocation *)invocation
{
	[self terminateDaemon];
	[*/
	

@end
